<template>
  <div>
<!-- 搜索页面头部 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon name="arrow-left" color="white" size="0.48rem" class="goback" @click="$router.back()"/>
      <!-- 搜索组件 -->
      <van-search
        v-model="kw"
        placeholder="请输入搜索关键词"
        background="#007BFF"
        shape="round"
        v-myfocus
        @input="inputFn"
        @search="moveResultPage"
      />
    </div>
    <!-- 搜索建议列表,与搜索历史列表是互斥的 -->
    <div class="sugg-list" v-if="suggestList.length!==0">
      <div class="sugg-item" v-for="(suggest,index) in suggestList" :key="index" v-html="highLight(suggest,kw)" @click="moveResultPage(suggest)">
          <!-- <HighLight :suggestText="suggest" :keyWord="kw"></HighLight> -->
      </div>
    </div>
    <!-- 搜索历史 -->
    <div class="search-history" v-else>
      <!-- 标题 -->
      <van-cell title="搜索历史">
          <!-- 使用 right-icon 插槽来自定义右侧图标 -->
          <template #right-icon>
            <van-icon name="delete" class="search-icon" @click="deleteHistory"/>
          </template>
      </van-cell>

    <!-- 历史列表 -->
    <div class="history-list">
        <span class="history-item" v-for="(keyword,index) in historyKey" :key="index" @click="moveResultPage(keyword)">{{keyword}}</span>
    </div>
</div>
  </div>
</template>

<script>
import { suggestListAPI } from '@/api/index'
import { localStorage } from '@/utils/storage'
// import HighLight from '@/components/HighLight.vue'
export default {
  name: 'Search',
  // components: { HighLight },
  data () {
    return {
      kw: '', // 搜索关键字
      timer: null, // 防抖定时器
      suggestList: [], // 搜索提示
      historyKey: [] // 搜索历史,暂无后端接口。本地模拟数据
    }
  },
  methods: {
    // =============获取输入框的内容=============
    async inputFn () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      // 防抖
      this.timer = setTimeout(async () => {
        if (this.kw.trim().length === 0) {
          // 清空搜索建议列表
          this.suggestList = []
          return
        }
        const res = await suggestListAPI({
          query: this.kw
        })
        this.suggestList = res.data.data.options
      }, 300)
    },
    // =============处理字符串高亮显示===========
    // originStr: 原字符串， target：关键词
    highLight (originStr, target) {
      // 搜索结果不为空
      if (originStr !== '') {
        const reg = new RegExp(target, 'ig')
        return originStr.replace(reg, (match) => {
          // match是匹配中的字符串
          return `<font color=red>${match}</font>`
        })
      }
    },
    // =============跳转到搜索结果页面=========
    // 1.搜索框输入后按下回车,默认参数
    // 2.点击联想菜单
    // 3.点击历史记录
    moveResultPage (key = this.kw) {
      // 保存本地的搜索记录
      this.saveHistoryKeyWord(key)
      this.$router.push({
        name: 'result',
        params: { kw: key }
      })
    },
    // =============保存搜索历史==================
    saveHistoryKeyWord (keyWord) {
      console.log(keyWord)
      if (!this.historyKey.includes(keyWord)) {
        this.historyKey.unshift(keyWord)
        // 保存到本地
        localStorage.set('keyWord', this.historyKey)
      }
    },
    // =============删除搜索历史=================
    deleteHistory () {
      this.historyKey = []
      // 保存到本地
      localStorage.set('keyWord', this.historyKey)
    }
  },
  mounted () {
    this.historyKey = localStorage.get('keyWord')
  }
}
</script>

<style lang='less' scoped>
  .search-header {
  height: 46px;
  display: flex;
  align-items: center;
  background-color: #007bff;
  overflow: hidden;
  /*后退按钮*/
  .goback {
    padding-left: 14px;
  }
  /*搜索组件*/
  .van-search {
    flex: 1;
  }
  }

  /*搜索建议列表样式 */
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #eee;
    font-size: 16px;
    line-height: 32px;
    // 实现省略号的三行代码
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
/**搜索历史 */
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
